<template>
  <div class="book-detail">
    <!-- 返回箭头按钮 -->
    <button class="back-btn" @click="goBack">← 返回</button>

    <el-card shadow="hover">
      <div class="book-info" v-if="book">
        <img :src="book.coverUrl" class="cover" />
        <div class="info">
          <h2>{{ book.title }}</h2>
          <p><strong>作者：</strong>{{ book.author }}</p>
          <p class="desc">{{ book.description }}</p>
        </div>
      </div>
    </el-card>

    <!-- 章节列表 -->
    <div class="chapter-list" v-if="book">
      <h3>章节预览</h3>
      <ul>
        <li v-for="(chapter, index) in visibleChapters" :key="index">
          <!-- 使用router-link让章节标题可点击跳转 -->
          <router-link
            :to="{
              name: 'bookChapter',
              params: { bookId: bookId, chapterId: chapter.chapterId },
            }"
            class="chapter-link"
          >
            {{ chapter.title }}
          </router-link>
        </li>
      </ul>

      <!-- 查看更多按钮 -->
      <el-button
        v-if="!showAll"
        @click="goToChapterList"
        type="text"
        class="more-chapters"
        >查看更多章节</el-button
      >
    </div>

    <!-- 按钮区域 -->
    <!-- 按钮区域 -->
    <div class="actions" v-if="book">
      <el-button type="primary" plain @click="goToFirstChapter">
        开始阅读
      </el-button>
      <el-button
        type="success"
        plain
        @click="book.isInShelf ? handleRemoveFromShelf() : handleAddToShelf()"
      >
        {{ book.isInShelf ? '移除书架' : '加入书架' }}
      </el-button>

      <el-button
        type="warning"
        plain
        @click="goToCharacters"
        class="character-btn"
      >
        <el-icon><User /></el-icon>
        主要人物
      </el-button>
    </div>
    <teleport to="body">
      <!-- 过渡动画 -->
      <transition name="dialog-fade">
        <!-- 遮罩层 -->
        <div
          v-if="showConfirmDialog"
          class="confirm-mask"
          @click.self="showConfirmDialog = false"
        >
          <!-- 弹窗内容 -->
          <div class="confirm-dialog">
            <div class="dialog-header">
              <h3>加入书架确认</h3>
            </div>
            <div class="dialog-content">
              <p>确定要将《{{ book?.title }}》加入书架吗？</p>
            </div>
            <div class="dialog-footer">
              <el-button @click="showConfirmDialog = false">取消</el-button>
              <el-button type="primary" @click="confirmAddToShelf"
                >确定</el-button
              >
            </div>
          </div>
        </div>
      </transition>
    </teleport>

    <teleport to="body">
      <transition name="dialog-fade">
        <div
          v-if="showRemoveDialog"
          class="confirm-mask"
          @click.self="showRemoveDialog = false"
        >
          <div class="confirm-dialog">
            <div class="dialog-header">
              <h3>移除书架确认</h3>
            </div>
            <div class="dialog-content">
              <p>确定要将《{{ book?.title }}》从书架移除吗？</p>
            </div>
            <div class="dialog-footer">
              <el-button @click="showRemoveDialog = false">取消</el-button>
              <el-button type="danger" @click="confirmRemoveFromShelf"
                >移除</el-button
              >
            </div>
          </div>
        </div>
      </transition>
    </teleport>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router' // 导入useRouter
import { getBookDetail, addBookToShelf, removeBookFromShelf } from '@/apis/book'
import { User } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter() // 获取router对象
const bookId = route.params.bookId

const book = ref(null)
const chapters = ref([])

// 状态来控制是否显示所有章节
const showAll = ref(false)

// 计算要显示的章节
const visibleChapters = computed(() => {
  return showAll.value ? chapters.value : chapters.value.slice(0, 5)
})

onMounted(async () => {
  try {
    const response = await getBookDetail(bookId)
    const bookData = response.data
    book.value = {
      bookId: bookData.bookId,
      title: bookData.title,
      author: bookData.author,
      description: bookData.description,
      coverUrl: bookData.coverUrl,
      isInShelf: bookData.isInShelf,
    }
    chapters.value = bookData.chapters || []
  } catch (error) {
    console.error('Failed to fetch book details:', error)
  }
})

// 返回上一页
const goBack = () => {
  router.push('/home/reading/library')
}

const goToChapterList = () => {
  router.push({ name: 'bookChapters', params: { bookId: bookId } })
}

const goToCharacters = () => {
  router.push({ name: 'bookCharacters', params: { bookId: bookId } }) // 跳转到 '/home/reading/book/:bookId/characters'
}

const goToFirstChapter = () => {
  if (chapters.value.length > 0) {
    const firstChapterId = chapters.value[0].chapterId
    router.push({
      name: 'bookChapter',
      params: { bookId: bookId, chapterId: firstChapterId },
    })
  } else {
    console.warn('章节列表为空，无法跳转')
  }
}

// 新增状态控制弹窗显示
const showConfirmDialog = ref(false)
const handleAddToShelf = () => {
  if (book.value.isInShelf) return
  showConfirmDialog.value = true // ✅ 只控制弹窗显示
}
// 修改后的确认方法
const confirmAddToShelf = async () => {
  try {
    const res = await addBookToShelf(bookId)
    if (res.code === '200') {
      book.value.isInShelf = true
      ElMessage.success('成功加入书架')
    } else {
      ElMessage.error(res.message || '加入书架失败')
    }
  } catch (error) {
    console.error('加入失败:', error)
    ElMessage.error('加入书架失败，请稍后重试')
  } finally {
    showConfirmDialog.value = false // ✅ 无论成功失败都关闭弹窗
  }
}

const showRemoveDialog = ref(false)
const handleRemoveFromShelf = () => {
  showRemoveDialog.value = true
}

const confirmRemoveFromShelf = async () => {
  try {
    // ❗️你需要实现这个 API 方法
    const res = await removeBookFromShelf(bookId)
    if (res.code === '200') {
      book.value.isInShelf = false
      ElMessage.success('已移出书架')
    } else {
      ElMessage.error(res.message || '移除失败')
    }
  } catch (error) {
    console.error('移除失败:', error)
    ElMessage.error('移除失败，请稍后重试')
  } finally {
    showRemoveDialog.value = false
  }
}
</script>

<style scoped>
.book-detail {
  padding: 20px;
}

.cover {
  width: 180px;
  height: 260px;
  object-fit: cover;
  border-radius: 8px;
}

.book-info {
  display: flex;
  gap: 20px;
}

.info {
  flex: 1;
}

.desc {
  margin-top: 12px;
  color: #666;
}

.chapter-list {
  margin-top: 24px;
}

.chapter-list h3 {
  margin-bottom: 8px;
}

.chapter-list ul {
  list-style: none;
  padding-left: 0;
  max-height: 250px;
  overflow: hidden;
  font-size: 14px;
  color: #333;
  line-height: 1.8;
}

.chapter-list li {
  padding: 4px 0;
}

/* 样式：为章节标题添加下划线 */
.chapter-link {
  color: #333;
  cursor: pointer;
}

.chapter-link:hover {
  color: #007bff;
  text-decoration: underline;
}

.actions {
  margin-top: 20px;
  display: flex;
  gap: 16px;
}

.more-chapters {
  margin-top: 10px;
  text-align: center;
  cursor: pointer;
}

.back-btn {
  background: none;
  border: none;
  color: #007bff;
  font-size: 16px;
  cursor: pointer;
}

/* 新增人物按钮样式 */
.character-btn {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

.character-btn:hover {
  background-color: #e1f3d8;
  border-color: #c2e7b0;
  color: #5daf34;
}

.character-btn:active {
  background-color: #c2e7b0;
}

/* 调整按钮间距 */
.actions {
  gap: 12px;
}

/* 图标样式 */
.el-icon {
  vertical-align: middle;
  margin-right: 6px;
  font-size: 16px;
}

/* 遮罩层样式 */
.confirm-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

/* 弹窗容器 */
.confirm-dialog {
  background: white;
  border-radius: 8px;
  width: 400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 弹窗内容布局 */
.dialog-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.dialog-content {
  padding: 24px 16px;
  font-size: 16px;
}

.dialog-footer {
  padding: 16px;
  text-align: right;
  border-top: 1px solid #eee;
}

/* 过渡动画 */
.dialog-fade-enter-active,
.dialog-fade-leave-active {
  transition: opacity 0.3s;
}

.dialog-fade-enter-from,
.dialog-fade-leave-to {
  opacity: 0;
}

.dialog-fade-enter-active .confirm-dialog,
.dialog-fade-leave-active .confirm-dialog {
  transition: transform 0.3s;
}

.dialog-fade-enter-from .confirm-dialog,
.dialog-fade-leave-to .confirm-dialog {
  transform: translateY(-20px);
}
</style>
